<template>
  <el-container id="publish">
    <el-header style="background: #2b334a;" class="text-white text-center">
      <h4 style="line-height: 60px;display: inline;float: left"> 图像标注系统 </h4>
      <h5 style="line-height: 60px;display: inline" >{{ imgObj.name }}</h5>
      <span style="float: right;height: 60px;padding: 10px 0">
        <el-button @click="handleFullScreen" :icon="fullscreen ? 'el-icon-crop' : 'el-icon-full-screen'" size="small"></el-button>
      </span>
    </el-header>
    <el-container>
      <el-aside style="width:100px;background:#1f273c;padding: 10px 5px;border-right: 1px solid #0c62ac">
        <el-button @click="goBack" size="small" type="text">
          <i class="el-icon-back"></i>
          <span style="margin-left: 10px">返回</span>
        </el-button>
        <el-divider></el-divider>
        <div >
          <el-menu
              text-color="#fff"
              background-color="#1f273c"
              active-text-color="#ffd04b"
              @select="handleMenu"
              style="border: none">
            <el-menu-item index="1" >
              <i class="fa fa-fold" style="margin-right: 10px;line-height: 23px;"> </i>
              <template #title>
                <input class="openFolderInput" type="file" multiple @change="changeFolder" />
              </template>
            </el-menu-item>
            <el-menu-item index="2" >
              <i  lass="fa fa-download" style="margin-right: 10px;line-height: 23px;"> </i>
              <template #title> 下载标注 </template>
            </el-menu-item>
          </el-menu>
        </div>

        <el-divider></el-divider>
        <div >
            <el-menu
                :default-active="0"
                text-color="#fff"
                background-color="#1f273c"
                active-text-color="#ffd04b"
                @select="changeToolType"
            style="border: none">
              <el-menu-item :index="item.type" v-for="item in toolOptions">
                <i :class="item.icon" style="margin-right: 10px;line-height: 23px;"> </i>
                <template #title>{{item.tip}}</template>
              </el-menu-item>
            </el-menu>
        </div>
      </el-aside>
      <el-main class="canvasMain">
        <div class="canvasContent">
          <canvas id="canvas"></canvas>
        </div>
      </el-main>
      <el-aside style="width:200px;background:#1f273c;padding: 10px 5px;border-left: 1px solid #0c62ac;color: ghostwhite">
        <div class="resultArea">
          <div class="p-2"> 标注结果 ({{resultTags.length}})</div>
          <el-table
              :data="resultTags"
              style="width: 190px;"
              ref="tableResultTags">
            <el-table-column
                prop="labelName"
                label="名称"
                width="90">
            </el-table-column>
            <el-table-column
                label="操作"
                width="100">
              <template #default="scope">
                <el-button type="text" style="color: red" @click="handleTagResultDel(scope.$index)">  <i class="el-icon-delete"> </i></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="p-2"> 标签管理
            <el-button @click="handleTagAdd" type="text" class="float-right"> <i class="el-icon-plus"></i>添加 </el-button>
          </div>
          <el-table
              :data="imgTags"
              style="width: 190px;"
              max-height="250">
            <el-table-column
                label="快捷键"
                width="60">
              <template #default="scope">
                <el-tag> {{scope.row.key}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
                prop="name"
                label="名称"
                width="120">
            </el-table-column>
          </el-table>

        </div>

      </el-aside>
    </el-container>
  </el-container>

  <el-dialog
      title="标签管理"
      v-model="formTagShow"
      width="50%"
      center>
    <el-form :model="formTag"  label-position="left" label-width="90px" >
      <el-form-item label="标签名称">
        <el-input v-model="formTag.name" autocomplete="off" style="width: 320px;"></el-input>
        <el-button type="primary" @click="confirmTagAdd" class="ml-2"> 添加</el-button>
      </el-form-item>
      <el-form-item label="已有标签" >
        <div>
          <el-tag v-for="item in imgTags" class="ml-2">{{item.name}} </el-tag>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="formTagShow = false">完成</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
// import LabelTool from './tools.vue'
// import GraphCanvas from './graphCanvas.vue'
import LabelImage from "/src/utils/graph/webAnnotate"
import { ref, defineComponent, onMounted, reactive, Ref } from 'vue'
import {ElMessage} from "element-plus";


export default defineComponent({
  name: 'Label',
  setup: () => {
    const formTagShow = ref<boolean>(false)
    const imgObj = reactive({
      name: 'a.jpg',
      url: 'https://pic2.zhimg.com/v2-d4642ff4024b1da82096e6e1cfb17d94_r.jpg?source=1940ef5c',
      width: 0,
      height: 0
    })
    const fullscreen = ref(false)
    const toolType = ref(0)
    const formTag = ref({name:''})
    const imgTags = ref([{key:1,name:'car'}])
    const resultTags  = reactive([])
    const editIndex = ref(0)
    let annotate: any = null
    const tableResultTags:Ref<any> = ref()
    function selectImage(imgObj:any) {
      if (imgObj){
        annotate.SetImage(imgObj.url, false)
      }
    }
    function confirmTagDraw(tag) {
      console.log('confirmTagDraw',resultTags)
      resultTags.push(tag)
      console.log('confirmTagDraw',resultTags)
    }
    onMounted(() => {
      const canvas = document.getElementById('canvas')
      // console.log('graph mounted',canvas.clientWidth,canvas.clientHeight)
      // canvas.style.width = canvas.clientWidth
      // canvas.style.height = canvas.clientHeight - 1

      let obj = {
        id: 1,
        url: 'https://pic2.zhimg.com/v2-d4642ff4024b1da82096e6e1cfb17d94_r.jpg?source=1940ef5c',
        width: 1280,
        height: 800
      }
      annotate = new LabelImage({
        canvas: canvas,
        drawCallback: confirmTagDraw
      })
      annotate.SetImage(imgObj.url, false)
      document.onkeydown = function(e) {
        // 事件对象兼容
        let e1 = e || event || window.event || arguments.callee.caller.arguments[0]
        if (!e1) {
          return
        }
        // 键盘按键判断:左箭头-37;上箭头-38；右箭头-39;下箭头-40,0-48 ~ 9-57
        if (e1 && e1.keyCode == 37) {
          console.log('<<')
        // } else if (e1 && e1.keyCode == 38) {
        //   console.log('^^')
        } else if (e1 && e1.keyCode == 39) {
          console.log('>>')
        // } else if (e1 && e1.keyCode == 40) {
        //   console.log('||')
        } else if (e1.keyCode >48 &&  e1.keyCode < 57) {
          // 数字按键
          let name = imgTags.value[e1.keyCode-49].name
          annotate.updateLabel(name)
          resultTags[editIndex.value-1].labelName = name
          tableResultTags.value.doLayout() // table刷新
        }
      }
      if (imgTags.value.length < 1) {
        formTagShow.value = true
      }
    })

    function handleTagAdd() {
      formTagShow.value = true
      // ElMessage('只是一条消息提示')
    }
    function confirmTagAdd() {
      // 去掉空格 差重复
      const name = formTag.value.name.replace( /\s+/g,'')
      if (name.length < 1) {
        return
      }
      for (let v of imgTags.value) {
        if (v.name === name) {
          return
        }
      }
      let tag = {
        name: name,
        key: imgTags.value.length + 1
      }
      imgTags.value.push(tag)
      editIndex.value = imgTags.value.length
    }

    function changeToolType(type:int) {
      toolType.value = type
      switch (type) {
        case 0: annotate.SetFeatures('dragOn', true); break;
        case 1: annotate.SetFeatures('rectOn', true); break;
        case 2: annotate.SetFeatures('rectOn', true); break;
        case 3: annotate.SetFeatures('polygonOn', true); break;
      }
    }
    function handleTagResultDel(index:int) {
      annotate.DeleteSomeResultLabel(index)
      resultTags.splice(index,1)
    }
    return {
      imgObj,
      resultTags,
      fullscreen,
      toolType,
      changeToolType,
      imgTags,
      formTag,
      formTagShow,
      confirmTagAdd,
      handleTagAdd,
      base64: '',
      toolOptions: [
        { icon: 'fa fa-mouse-pointer ', type: 0, tip: '拖到' },
        { icon: 'fa fa-square-o ', type: 1, tip: '矩形' },
        { icon: 'fa fa-circle-o ', type: 2, tip: '圆形' },
        { icon: 'fa fa-certificate', type: 3, tip: '多边' }
      ],
      handleTagResultDel,
      changeFolder: (e:Event) => {
        if (e && e.target) {
          let files = e.target.files
          let name = files[0].name || files[0].split('/')[3];
          imgObj.name = name
          imgObj.url = window.URL.createObjectURL(files[0])
          console.log(files[0])
          annotate.SetImage(imgObj.url, false)
        }
      },
      tableResultTags,
      handleMenu: (index) => {
        switch (index) {
          case 1: annotate.SetFeatures('dragOn', true); break; // 打开文件夹
          // case 2: handleSaveJson();break
        }
      },
      handleFullScreen: ()=>{
        let element = document.documentElement;
        fullscreen.value = !fullscreen.value
        if (!fullscreen.value) {
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen(); // IE11
          }
        } else {    // 否则，进入全屏
          if (element.requestFullscreen) {
            element.requestFullscreen();
          } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen();
          } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
          } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
          }
        }
      },
      handleSaveJson: () => {
          if (resultTags.length < 1) {
            ElMessage.error('没有标注数据')
          }
          let fileName = imgObj.name + '.json'
          let data = JSON.stringify(resultTags, undefined, 4);

          let blob = new Blob([data], {type: 'text/json'}),
              e = document.createEvent('MouseEvent'),
              a = document.createElement('a');
          a.download = fileName;
          a.href = window.URL.createObjectURL(blob);
          a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
          e.initMouseEvent('click', true, false, window,  0, 0, 0, 0, 0, false, false, false, false, 0, null);
          a.dispatchEvent(e)
        }
    }
  },
  methods: {
    //返回
    goBack() {
      this.$router.go(-1)
    },

    // 恢复初始自适应状态
    fixToAutoWH() {
      this.$refs["exprtCanvas"].fixToAutoWH()
    },
    // 获取canvas base64图
    getBase64() {
      this.base64 = this.$refs["exprtCanvas"].getBase64();
    }
  }
})
</script>


<style lang="scss" scoped>
@import "/src/assets/label.css";
#publish {
  position: relative;
  background: #8c919c;
  height: 100%;
}
.choosed-tool-type {
  color: #409eff;
  border-color: #409eff;
}
</style>